package com.ruoyi.station.controller;

import java.util.List;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.Arith;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.station.domain.QueryData;
import com.ruoyi.station.domain.SDistributionFrame;
import com.ruoyi.station.domain.SEquipment;
import com.ruoyi.station.domain.SMachineRoom;
import com.ruoyi.station.service.SDistributionFrameService;
import com.ruoyi.station.service.SMachineCabinetService;
import com.ruoyi.station.util.ParseSql;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.multipart.MultipartFile;

/**
 * 配线架Controller
 *
 * @author ruoyi
 * @date 2021-08-06
 */
@RestController
@RequestMapping("/frame")
@Api(value="配线架对象操作资源", tags = "配线架对象操作资源")
public class SDistributionFrameController extends BaseController
{
    @Autowired
    private SDistributionFrameService sDistributionFrameService;

    @Autowired
    private TokenService tokenService;
    @Autowired
    private SMachineCabinetService sMachineCabinetService;
    @Autowired
    private ISysUserService iSysUserService;
    /**
     * 查询配线架列表
     */
    @PreAuthorize("@ss.hasPermi('system:frame:list')")
    @PostMapping("/list")
    @ApiOperation(value="查询配线架列表", notes="查询配线架列表")
    public TableDataInfo query(@ApiParam @RequestBody Map map)
    {
        JSONArray queryData = JSONUtil.parseArray(map.get("queryData"));
        Integer pageNum = (Integer) map.get("pageNum");
        Integer pageSize = (Integer) map.get("pageSize");
        startPage(pageNum , pageSize);
        List<String> userList = iSysUserService.selectUserByDept(SecurityUtils.getLoginUser().getUser().getDeptId());
        QueryWrapper<SDistributionFrame> wrapper = new QueryWrapper<>();
        Page s = new Page<>(pageNum,pageSize);
        Page<SDistributionFrame> list = sDistributionFrameService.page(s,ParseSql.parse(wrapper, JSONUtil.toList(queryData, QueryData.class),userList));
        return getTableDataInfo(list.getRecords(),list.getTotal());
    }

    /**
     * 查询配线架列表
     */
    @PreAuthorize("@ss.hasPermi('system:frame:list')")
    @GetMapping("/list")
    @ApiOperation(value="查询配线架列表", notes="查询配线架列表")
    public TableDataInfo list(@ApiParam SDistributionFrame sDistributionFrame)
    {
        QueryWrapper<SDistributionFrame> wrapper = new QueryWrapper();
        //通过部门ID获取同部门的所有员工
        List<String> userList = iSysUserService.selectUserByDept(SecurityUtils.getLoginUser().getUser().getDeptId());
        Set<String> userByRoleSet = ParseSql.getUserByRoleUtil(userList);
        if (userByRoleSet != null && userByRoleSet.size() > 0){
            wrapper.in("create_by",userByRoleSet);
        }
        List<SDistributionFrame> list = sDistributionFrameService.list(wrapper);
        return getDataTable(list);
    }

    /**
     * 根据配线架行列生成端口组数据
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:frame:portgroup')")
    @GetMapping("/createPortGroup/{id}")
    @ApiOperation(value="生成端口", notes="生成端口")
    public AjaxResult createPortGroup(@PathVariable String id)
    {

        SDistributionFrame byId = sDistributionFrameService.getById(id);
        int portColumn = byId.getPortColumn();
        int portLine = byId.getPortLine();
        int mul = (int) Arith.mul(portColumn, portLine);
        String portGroup = "";
        for (int i = 1; i < mul+1; i++) {
            portGroup += "#"+ i+",";
        }
        byId.setPortGroupData(portGroup.substring(0,portGroup.length()-1));
        byId.setUpdateFlag(0);
        boolean b = sDistributionFrameService.updateById(byId);
        if (b)return AjaxResult.success("创建成功");
        return AjaxResult.error("创建失败");
    }


    /**
     * 导出配线架列表
     */
    @PreAuthorize("@ss.hasPermi('system:frame:export')")
    @Log(title = "配线架", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    @ApiOperation(value="导出配线架列表", notes="导出配线架列表")
    public AjaxResult export(@ApiParam SDistributionFrame sDistributionFrame)
    {
        QueryWrapper<SDistributionFrame> wrapper = new QueryWrapper();
        //通过部门ID获取同部门的所有员工
        List<String> userList = iSysUserService.selectUserByDept(SecurityUtils.getLoginUser().getUser().getDeptId());
        Set<String> userByRoleSet = ParseSql.getUserByRoleUtil(userList);
        if (userByRoleSet != null && userByRoleSet.size() > 0){
            wrapper.in("create_by",userByRoleSet);
        }
        List<SDistributionFrame> list = parse(sDistributionFrameService.list(wrapper));
        ExcelUtil<SDistributionFrame> util = new ExcelUtil<SDistributionFrame>(SDistributionFrame.class);
        return util.exportExcel(list, "frame");
    }

    /**
     * 导出数据转换
     * @param list
     * @return
     */
    private List<SDistributionFrame> parse(List<SDistributionFrame> list){
        list.stream().forEach(l -> {
            l.setMachineCabinet(sMachineCabinetService.getById(l.getMachineCabinet()).getMachineCabinetName());
            l.setDistributionFrameType(DictUtils.getDictLabel("frame_type",l.getDistributionFrameType()));
        });
        return list;
    }
    /**
     * 获取配线架详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:frame:query')")
    @GetMapping(value = "/{id}")
    @ApiOperation(value="获取配线架详细信息", notes="获取配线架详细信息")
    public AjaxResult getInfo(@ApiParam @PathVariable("id") String id)
    {
        return AjaxResult.success(sDistributionFrameService.getById(id));
    }

    /**
     * 新增配线架
     */
    @PreAuthorize("@ss.hasPermi('system:frame:add')")
    @Log(title = "配线架", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation(value="新增配线架", notes="新增配线架")
    public AjaxResult add(@ApiParam @RequestBody SDistributionFrame sDistributionFrame)
    {
        sDistributionFrame.setCreateBy(SecurityUtils.getUsername());
        int result = sDistributionFrameService.save(sDistributionFrame) == true ? 1 : 0;
        return toAjax(result);
    }

    /**
     * 修改配线架
     */
    @PreAuthorize("@ss.hasPermi('system:frame:edit')")
    @Log(title = "配线架", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation(value="修改配线架", notes="修改配线架")
    public AjaxResult edit(@ApiParam @RequestBody SDistributionFrame sDistributionFrame)
    {
        SDistributionFrame byId = sDistributionFrameService.getById(sDistributionFrame.getId());
        int portLine = sDistributionFrame.getPortLine();
        int portColumn = sDistributionFrame.getPortColumn();
        if (portColumn != byId.getPortColumn() || portLine != byId.getPortLine()){
            sDistributionFrame.setUpdateFlag(1);//端口数据已修改
        }else {
            sDistributionFrame.setUpdateFlag(0);
        }
        int result = sDistributionFrameService.updateById(sDistributionFrame) == true ? 1 : 0;
        return toAjax(result);
    }

    /**
     * 删除配线架
     */
    @PreAuthorize("@ss.hasPermi('system:frame:remove')")
    @Log(title = "配线架", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @ApiOperation(value="删除配线架", notes="删除配线架")
    public AjaxResult remove(@ApiParam @PathVariable String[] ids)
    {
        List<String> list = Arrays.asList(ids);
        int result = sDistributionFrameService.removeByIds(list) == true ? 1 : 0;
        return toAjax(result);
    }

    /**
     * 导出配线架模板
     * @return
     */
    @GetMapping("/importTemplate")
    public AjaxResult importTemplate()
    {
        return AjaxResult.success("DLBDZ_配线架.xls");
    }

    @Log(title = "导入配线架管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:frame:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file)
    {
        String message = sDistributionFrameService.importsDistributionFrames(file);
        return AjaxResult.success(message);
    }
}
